home *** CD-ROM | disk | FTP | other *** search
/ Openstep 4.2 (Developer) / Openstep Developer 4.2.iso / NextDeveloper / Source / GNU / uucp / uucico / protg.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-20  |  56.8 KB  |  1,979 lines

  1. /* protg.c
  2.    The 'g' protocol.
  3.  
  4.    Copyright (C) 1991, 1992, 1993, 1994, 1995 Ian Lance Taylor
  5.  
  6.    This file is part of the Taylor UUCP package.
  7.  
  8.    This program is free software; you can redistribute it and/or
  9.    modify it under the terms of the GNU General Public License as
  10.    published by the Free Software Foundation; either version 2 of the
  11.    License, or (at your option) any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful, but
  14.    WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.    General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  21.  
  22.    The author of the program may be contacted at ian@airs.com or
  23.    c/o Cygnus Support, 48 Grove Street, Somerville, MA 02144.
  24.    */
  25.  
  26. #include "uucp.h"
  27.  
  28. #if USE_RCS_ID
  29. const char protg_rcsid[] = "$Id: protg.c,v 1.68 1995/06/21 19:15:22 ian Rel $";
  30. #endif
  31.  
  32. #include <ctype.h>
  33. #include <errno.h>
  34.  
  35. #include "uudefs.h"
  36. #include "uuconf.h"
  37. #include "conn.h"
  38. #include "trans.h"
  39. #include "system.h"
  40. #include "prot.h"
  41.  
  42. /* Each 'g' protocol packet begins with six bytes.  They are:
  43.  
  44.    <DLE><k><c0><c1><C><x>
  45.  
  46.    <DLE> is the ASCII DLE character (^P or '\020').
  47.    if 1 <= <k> <= 8, the packet is followed by 2 ** (k + 4) bytes of data;
  48.    if <k> == 9, these six bytes are a complete control packet;
  49.    other value of <k> are illegal.
  50.    <c0> is the low byte of a checksum.
  51.    <c1> is the high byte of a checksum.
  52.    <C> is a control byte (see below).
  53.    <x> is <k> ^ <c0> ^ <c1> ^ <C>.
  54.  
  55.    The control byte <C> is divided into three bitfields:
  56.  
  57.    t t x x x y y y
  58.  
  59.    The two bit field tt is the packet type.
  60.    The three bit field xxx is the control type for a control packet, or
  61.    the sequence number for a data packet.
  62.    The three bit field yyy is a value for a control packet, or the
  63.    sequence number of the last packet received for a data packet.
  64.  
  65.    For all successfully recieved packets, the control byte is stored
  66.    into iGpacket_control.  */
  67.  
  68. /* Names for the bytes in the frame header.  */
  69. #define IFRAME_DLE (0)
  70. #define IFRAME_K (1)
  71. #define IFRAME_CHECKLOW (2)
  72. #define IFRAME_CHECKHIGH (3)
  73. #define IFRAME_CONTROL (4)
  74. #define IFRAME_XOR (5)
  75.  
  76. /* Length of the frame header.  */
  77. #define CFRAMELEN (6)
  78.  
  79. /* Macros to break apart the control bytes.  */
  80. #define CONTROL_TT(b) ((int)(((b) >> 6) & 03))
  81. #define CONTROL_XXX(b) ((int)(((b) >> 3) & 07))
  82. #define CONTROL_YYY(b) ((int)((b) & 07))
  83.  
  84. /* DLE value.  */
  85. #define DLE ('\020')
  86.  
  87. /* Get the length of a packet given a pointer to the header.  */
  88. #define CPACKLEN(z) ((size_t) (1 << ((z)[IFRAME_K] + 4)))
  89.  
  90. /* <k> field value for a control message.  */
  91. #define KCONTROL (9)
  92.  
  93. /* Get the next sequence number given a sequence number.  */
  94. #define INEXTSEQ(i) ((i + 1) & 07)
  95.  
  96. /* Compute i1 - i2 modulo 8.  */
  97. #define CSEQDIFF(i1, i2) (((i1) + 8 - (i2)) & 07)
  98.  
  99. /* Packet types.  These are from the tt field.
  100.    CONTROL -- control packet
  101.    ALTCHAN -- alternate channel; not used by UUCP
  102.    DATA -- full data segment
  103.    SHORTDATA -- less than full data segment (all the bytes specified by
  104.    the packet length <k> are always transferred).  Let <u> be the number
  105.    of bytes in the data segment not to be used.  If <u> <= 0x7f, the first
  106.    byte of the data segment is <u> and the data follows.  If <u> > 0x7f,
  107.    the first byte of the data segment is 0x80 | (<u> & 0x7f), the second
  108.    byte of the data segment is <u> >> 7, and the data follows.  The
  109.    maximum possible data segment size is 2**12, so this handles all
  110.    possible cases.  */
  111. #define CONTROL (0)
  112. #define ALTCHAN (1)
  113. #define DATA (2)
  114. #define SHORTDATA (3)
  115.  
  116. /* Control types.  These are from the xxx field if the type (tt field)
  117.    is CONTROL.
  118.  
  119.    CLOSE -- close the connection
  120.    RJ -- reject; packet yyy last to be received correctly
  121.    SRJ -- selective reject; reject only packet yyy (not used by UUCP)
  122.    RR -- receiver ready; packet yyy received correctly
  123.    INITC -- third step of initialization; yyy holds window size
  124.    INITB -- second step of initialization; yyy holds maximum <k> value - 1
  125.    INITA -- first step of initialization; yyy holds window size.
  126.  
  127.    The yyy value for RR is the same as the yyy value for an ordinary
  128.    data packet.  */
  129. #define CLOSE (1)
  130. #define RJ (2)
  131. #define SRJ (3)
  132. #define RR (4)
  133. #define INITC (5)
  134. #define INITB (6)
  135. #define INITA (7)
  136.  
  137. /* Maximum amount of data in a single packet.  This is set by the <k>
  138.    field in the header; the amount of data in a packet is
  139.    2 ** (<k> + 4).  <k> ranges from 1 to 8.  */
  140.     
  141. #define CMAXDATAINDEX (8)
  142.  
  143. #define CMAXDATA (1 << (CMAXDATAINDEX + 4))
  144.  
  145. /* Maximum window size.  */
  146. #define CMAXWINDOW (7)
  147.  
  148. /* Defaults for the protocol parameters.  These may all be changed by
  149.    using the ``protocol-parameter g'' command, so there is no
  150.    particular reason to change the values given here.  */
  151.  
  152. /* The desired window size.  This is what we tell the other system to
  153.    use.  It must be between 1 and 7, and there's no reason to use less
  154.    than 7.  Protocol parameter ``window''.  */
  155. #define IWINDOW (7)
  156.  
  157. /* The desired packet size.  Many implementations only support 64 byte
  158.    packets.  Protocol parameter ``packet-size''.  */
  159. #define IPACKSIZE (64)
  160.  
  161. /* The number of times to retry the exchange of INIT packets when
  162.    starting the protocol.  Protocol parameter ``startup-retries''.  */
  163. #define CSTARTUP_RETRIES (8)
  164.  
  165. /* The timeout to use when waiting for an INIT packet when starting up
  166.    the protocol.  Protocol parameter ``init-timeout''.  */
  167. #define CEXCHANGE_INIT_TIMEOUT (10)
  168.  
  169. /* The number of times to retry sending and waiting for a single INIT
  170.    packet when starting the protocol.  This controls a single INIT
  171.    packet, while CSTARTUP_RETRIES controls how many times to try the
  172.    entire INIT sequence.  Protocol parameter ``init-retries''.  */
  173. #define CEXCHANGE_INIT_RETRIES (4)
  174.  
  175. /* The timeout to use when waiting for a packet.  Protocol parameter
  176.    ``timeout''.  */
  177. #define CTIMEOUT (10)
  178.  
  179. /* The number of times to retry waiting for a packet.  Each time the
  180.    timeout fails we send a copy of our last data packet or a reject
  181.    message for the packet we expect from the other side, depending on
  182.    whether we are waiting for an acknowledgement or a data packet.
  183.    This is the number of times we try doing that and then waiting
  184.    again.  Protocol parameter ``retries''.   */
  185. #define CRETRIES (6)
  186.  
  187. /* If we see more than this much unrecognized data, we drop the
  188.    connection.  This must be larger than a single packet size, which
  189.    means it must be larger than 4096 (the largest possible packet
  190.    size).  Protocol parameter ``garbage''.  */
  191. #define CGARBAGE (10000)
  192.  
  193. /* If we see more than this many protocol errors, we drop the
  194.    connection.  Protocol parameter ``errors''.  */
  195. #define CERRORS (100)
  196.  
  197. /* Default decay rate.  Each time we send or receive this many packets
  198.    succesfully, we decrement the error level by one (protocol
  199.    parameter ``error-decay'').  */
  200. #define CERROR_DECAY (10)
  201.  
  202. /* If this value is non-zero, it will be used as the remote window
  203.    size regardless of what the other side requested.  This can be
  204.    useful for dealing with some particularly flawed packages.  This
  205.    default value should always be 0, and protocol parameter
  206.    ``remote-window'' should be used for the affected systems.  */
  207. #define IREMOTE_WINDOW (0)
  208.  
  209. /* If this value is non-zero, it will be used as the packet size to
  210.    send to the remote system regardless of what it requested.  It's
  211.    difficult to imagine any circumstances where you would want to set
  212.    this.  Protocol parameter ``remote-packet-size''.  */
  213. #define IREMOTE_PACKSIZE (0)
  214.  
  215. /* Local variables.  */
  216.  
  217. /* Next sequence number to send.  */
  218. static int iGsendseq;
  219.  
  220. /* Last sequence number that has been acked.  */
  221. static int iGremote_ack;
  222.  
  223. /* Last sequence number to be retransmitted.  */
  224. static int iGretransmit_seq;
  225.  
  226. /* Last sequence number we have received.  */
  227. static int iGrecseq;
  228.  
  229. /* Last sequence number we have acked.  */
  230. static int iGlocal_ack;
  231.  
  232. /* Window size to request (protocol parameter ``window'').  */
  233. static int iGrequest_winsize = IWINDOW;
  234.  
  235. /* Packet size to request (protocol parameter ``packet-size'').  */
  236. static int iGrequest_packsize = IPACKSIZE;
  237.  
  238. /* Remote window size (set during handshake).  */
  239. static int iGremote_winsize;
  240.  
  241. /* Forced remote window size (protocol parameter ``remote-window'').  */
  242. static int iGforced_remote_winsize = IREMOTE_WINDOW;
  243.  
  244. /* Remote segment size (set during handshake).  This is one less than
  245.    the value in a packet header.  */
  246. static int iGremote_segsize;
  247.  
  248. /* Remote packet size (set based on iGremote_segsize).  */
  249. static size_t iGremote_packsize;
  250.  
  251. /* Forced remote packet size (protocol parameter
  252.    ``remote-packet-size'').  */
  253. static int iGforced_remote_packsize = IREMOTE_PACKSIZE;
  254.  
  255. /* Recieved control byte.  */
  256. static int iGpacket_control;
  257.  
  258. /* Number of times to retry the initial handshake.  Protocol parameter
  259.    ``startup-retries''.  */
  260. static int cGstartup_retries = CSTARTUP_RETRIES;
  261.  
  262. /* Number of times to retry sending an initial control packet.
  263.    Protocol parameter ``init-retries''.  */
  264. static int cGexchange_init_retries = CEXCHANGE_INIT_RETRIES;
  265.  
  266. /* Timeout (seconds) for receiving an initial control packet.
  267.    Protocol parameter ``init-timeout''.  */
  268. static int cGexchange_init_timeout = CEXCHANGE_INIT_TIMEOUT;
  269.  
  270. /* Timeout (seconds) for receiving a data packet.  Protocol parameter
  271.    ``timeout''.  */
  272. static int cGtimeout = CTIMEOUT;
  273.  
  274. /* Maximum number of timeouts when receiving a data packet or
  275.    acknowledgement.  Protocol parameter ``retries''.  */
  276. static int cGretries = CRETRIES;
  277.  
  278. /* Amount of garbage data we are prepared to see before giving up.
  279.    Protocol parameter ``garbage''.  */
  280. static int cGgarbage_data = CGARBAGE;
  281.  
  282. /* Maximum number of errors we are prepared to see before giving up.
  283.    Protocol parameter ``errors''.  */
  284. static int cGmax_errors = CERRORS;
  285.  
  286. /* Each time we receive this many packets succesfully, we decrement
  287.    the error level by one (protocol parameter ``error-decay'').  */
  288. static int cGerror_decay = CERROR_DECAY;
  289.  
  290. /* Whether to use shorter packets when possible.  Protocol parameter
  291.    ``short-packets''.  */
  292. static boolean fGshort_packets = TRUE;
  293.  
  294. /* Protocol parameter commands.  */
  295. struct uuconf_cmdtab asGproto_params[] =
  296. {
  297.   { "window", UUCONF_CMDTABTYPE_INT, (pointer) &iGrequest_winsize, NULL },
  298.   { "packet-size", UUCONF_CMDTABTYPE_INT, (pointer) &iGrequest_packsize,
  299.       NULL },
  300.   { "startup-retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGstartup_retries,
  301.       NULL },
  302.   { "init-timeout", UUCONF_CMDTABTYPE_INT, (pointer) &cGexchange_init_timeout,
  303.       NULL },
  304.   { "init-retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGexchange_init_retries,
  305.       NULL },
  306.   { "timeout", UUCONF_CMDTABTYPE_INT, (pointer) &cGtimeout, NULL },
  307.   { "retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGretries, NULL },
  308.   { "garbage", UUCONF_CMDTABTYPE_INT, (pointer) &cGgarbage_data, NULL },
  309.   { "errors", UUCONF_CMDTABTYPE_INT, (pointer) &cGmax_errors, NULL },
  310.   { "error-decay", UUCONF_CMDTABTYPE_INT, (pointer) &cGerror_decay, NULL },
  311.   { "remote-window", UUCONF_CMDTABTYPE_INT,
  312.       (pointer) &iGforced_remote_winsize, NULL },
  313.   { "remote-packet-size", UUCONF_CMDTABTYPE_INT,
  314.       (pointer) &iGforced_remote_packsize, NULL },
  315.   { "short-packets", UUCONF_CMDTABTYPE_BOOLEAN, (pointer) &fGshort_packets,
  316.       NULL },
  317.   { NULL, 0, NULL, NULL }
  318. };
  319.  
  320. /* Statistics.  */
  321.  
  322. /* Number of packets we have sent.  */
  323. static long cGsent_packets;
  324.  
  325. /* Number of packets we have resent (these are not included in
  326.    cGsent_packets).  */
  327. static long cGresent_packets;
  328.  
  329. /* Number of packets we have delayed sending (these should not be
  330.    counted in cGresent_packets).  */
  331. static long cGdelayed_packets;
  332.  
  333. /* Number of packets we have received.  */
  334. static long cGrec_packets;
  335.  
  336. /* Number of packets rejected because the header was bad.  */
  337. static long cGbad_hdr;
  338.  
  339. /* Number of packets rejected because the checksum was bad.  */
  340. static long cGbad_checksum;
  341.  
  342. /* Number of packets received out of order.  */
  343. static long cGbad_order;
  344.  
  345. /* Number of packets rejected by receiver (number of RJ packets
  346.    received).  */
  347. static long cGremote_rejects;
  348.  
  349. /* Number of duplicate RR packets treated as RJ packets.  Some UUCP
  350.    packages appear to never send RJ packets, but only RR packets.  If
  351.    no RJ has been seen, fgprocess_data treats a duplicate RR as an RJ
  352.    and increments this variable.  */
  353. static long cGremote_duprrs;
  354.  
  355. /* The error level.  This is the total number of errors as adjusted by
  356.    cGerror_decay.  */
  357. static long cGerror_level;
  358.  
  359. /* Each time we send an RJ, we can expect several out of order of
  360.    packets, because the other side will probably have sent a full
  361.    window by the time it sees the RJ.  This variable keeps track of
  362.    the number of out of order packets we expect to see.  We don't
  363.    count expected out of order packets against the error level.  This
  364.    is reset to 0 when an in order packet is received.  */
  365. static int cGexpect_bad_order;
  366.  
  367. #if DEBUG > 1
  368. /* Control packet names used for debugging.  */
  369. static const char * const azGcontrol[] =
  370. {"?0?", "CLOSE", "RJ", "SRJ", "RR", "INITC", "INITB", "INITA"};
  371. #endif
  372.  
  373. /* Local functions.  */
  374. static boolean fgexchange_init P((struct sdaemon *qdaemon, int ictl,
  375.                   int ival, int *piset));
  376. static boolean fgsend_control P((struct sdaemon *qdaemon, int ictl,
  377.                  int ival));
  378. static char *zgadjust_ack P((int iseq));
  379. static boolean fgwait_for_packet P((struct sdaemon *qdaemon,
  380.                     boolean freturncontrol, int ctimeout,
  381.                     int cretries));
  382. static boolean fgsend_acks P((struct sdaemon *qdaemon));
  383. static boolean fggot_ack P((struct sdaemon *qdaemon, int iack));
  384. static boolean fgprocess_data P((struct sdaemon *qdaemon, boolean fdoacks,
  385.                  boolean freturncontrol,
  386.                  boolean *pfexit, size_t *pcneed,
  387.                  boolean *pffound));
  388. static boolean fginit_sendbuffers P((boolean fallocate));
  389. static boolean fgcheck_errors P((struct sdaemon *qdaemon));
  390. static int igchecksum P((const char *zdata, size_t clen));
  391. static int igchecksum2 P((const char *zfirst, size_t cfirst,
  392.               const char *zsecond, size_t csecond));
  393.  
  394. /* Start the protocol.  This requires a three way handshake.  Both sides
  395.    must send and receive an INITA packet, an INITB packet, and an INITC
  396.    packet.  The INITA and INITC packets contain the window size, and the
  397.    INITB packet contains the packet size.  */
  398.  
  399. boolean
  400. fgstart (qdaemon, pzlog)
  401.      struct sdaemon *qdaemon;
  402.      char **pzlog;
  403. {
  404.   int iseg;
  405.   int i;
  406.   boolean fgota, fgotb;
  407.  
  408.   *pzlog = NULL;
  409.  
  410.   /* The 'g' protocol requires a full eight bit interface.  */
  411.   if (! fconn_set (qdaemon->qconn, PARITYSETTING_NONE,
  412.            STRIPSETTING_EIGHTBITS, XONXOFF_OFF))
  413.     return FALSE;
  414.  
  415.   iGsendseq = 1;
  416.   iGremote_ack = 0;
  417.   iGretransmit_seq = -1;
  418.   iGrecseq = 0;
  419.   iGlocal_ack = 0;
  420.   cGsent_packets = 0;
  421.   cGresent_packets = 0;
  422.   cGdelayed_packets = 0;
  423.   cGrec_packets = 0;
  424.   cGbad_hdr = 0;
  425.   cGbad_checksum = 0;
  426.   cGbad_order = 0;
  427.   cGremote_rejects = 0;
  428.   cGremote_duprrs = 0;
  429.   cGerror_level = 0;
  430.   cGexpect_bad_order = 0;
  431.  
  432.   /* We must determine the segment size based on the packet size
  433.      which may have been modified by a protocol parameter command.
  434.      A segment size of 2^n is passed as n - 5.  */
  435.   i = iGrequest_packsize;
  436.   iseg = -1;
  437.   while (i > 0)
  438.     {
  439.       ++iseg;
  440.       i >>= 1;
  441.     }
  442.   iseg -= 5;
  443.   if (iseg < 0 || iseg > 7)
  444.     {
  445.       ulog (LOG_ERROR, "Illegal packet size %d for '%c' protocol",
  446.         iGrequest_packsize, qdaemon->qproto->bname);
  447.       iseg = 1;
  448.     }
  449.   
  450.   if (iGrequest_winsize <= 0 || iGrequest_winsize > 7)
  451.     {
  452.       ulog (LOG_ERROR, "Illegal window size %d for '%c' protocol",
  453.         iGrequest_winsize, qdaemon->qproto->bname);
  454.       iGrequest_winsize = IWINDOW;
  455.     }
  456.  
  457.   fgota = FALSE;
  458.   fgotb = FALSE;
  459.   for (i = 0; i < cGstartup_retries; i++)
  460.     {
  461.       if (fgota)
  462.     {
  463.       if (! fgsend_control (qdaemon, INITA, iGrequest_winsize))
  464.         return FALSE;
  465.     }
  466.       else
  467.     {
  468.       if (! fgexchange_init (qdaemon, INITA, iGrequest_winsize,
  469.                  &iGremote_winsize))
  470.         continue;
  471.     }
  472.       fgota = TRUE;
  473.  
  474.       if (fgotb)
  475.     {
  476.       if (! fgsend_control (qdaemon, INITB, iseg))
  477.         return FALSE;
  478.     }
  479.       else
  480.     {
  481.       if (! fgexchange_init (qdaemon, INITB, iseg, &iGremote_segsize))
  482.         continue;
  483.     }
  484.       fgotb = TRUE;
  485.  
  486.       if (! fgexchange_init (qdaemon, INITC, iGrequest_winsize,
  487.                  &iGremote_winsize))
  488.     continue;
  489.  
  490.       /* We have succesfully connected.  Determine the remote packet
  491.      size.  */
  492.       iGremote_packsize = 1 << (iGremote_segsize + 5);
  493.  
  494.       /* If the user requested us to force specific remote window and
  495.      packet sizes, do so now.  */
  496.       if (iGforced_remote_winsize > 0
  497.       && iGforced_remote_winsize <= CMAXWINDOW)
  498.     iGremote_winsize = iGforced_remote_winsize;
  499.  
  500.       if (iGforced_remote_packsize >= 32
  501.       && iGforced_remote_packsize <= 4096)
  502.     {
  503.       /* Force the value to a power of two.  */
  504.       i = iGforced_remote_packsize;
  505.       iseg = -1;
  506.       while (i > 0)
  507.         {
  508.           ++iseg;
  509.           i >>= 1;
  510.         }
  511.       iGremote_packsize = 1 << iseg;
  512.       iGremote_segsize = iseg - 5;
  513.     }
  514.  
  515.       /* Set up packet buffers to use.  We don't do this until we know
  516.      the maximum packet size we are going to send.  */
  517.       if (! fginit_sendbuffers (TRUE))
  518.     return FALSE;
  519.  
  520.       *pzlog =
  521.     zbufalc (sizeof "protocol '' sending packet/window / receiving /"
  522.          + 64);
  523.       sprintf (*pzlog,
  524.            "protocol '%c' sending packet/window %d/%d receiving %d/%d",
  525.            qdaemon->qproto->bname, (int) iGremote_packsize,
  526.            (int) iGremote_winsize, (int) iGrequest_packsize,
  527.            (int) iGrequest_winsize);
  528.  
  529.       return TRUE;
  530.     }
  531.  
  532.   DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
  533.           "fgstart: Protocol startup failed");
  534.  
  535.   return FALSE;
  536. }
  537.  
  538. /* The 'G' protocol is identical to the 'g' protocol, except that
  539.    short packets are never supported.  */
  540.  
  541. boolean
  542. fbiggstart (qdaemon, pzlog)
  543.      struct sdaemon *qdaemon;
  544.      char **pzlog;
  545. {
  546.   fGshort_packets = FALSE;
  547.   return fgstart (qdaemon, pzlog);
  548. }
  549.  
  550. /* The 'v' protocol is identical to the 'g' protocol, except that the
  551.    packet size defaults to 512 bytes.  Rather than really get it
  552.    right, we automatically switch from the usual default of 64 to 512.
  553.    This won't work correctly if somebody does protocol-parameter v
  554.    packet-size 64.  */
  555.  
  556. boolean
  557. fvstart (qdaemon, pzlog)
  558.      struct sdaemon *qdaemon;
  559.      char **pzlog;
  560. {
  561.   if (iGrequest_packsize == IPACKSIZE)
  562.     iGrequest_packsize = 1024;
  563.   return fgstart (qdaemon, pzlog);
  564. }  
  565.  
  566. /* Exchange initialization messages with the other system.
  567.  
  568.    A problem:
  569.  
  570.    We send INITA; it gets received
  571.    We receive INITA
  572.    We send INITB; it gets garbled
  573.    We receive INITB
  574.  
  575.    We have seen and sent INITB, so we start to send INITC.  The other
  576.    side as sent INITB but not seen it, so it times out and resends
  577.    INITB.  We will continue sending INITC and the other side will
  578.    continue sending INITB until both sides give up and start again
  579.    with INITA.
  580.  
  581.    It might seem as though if we are sending INITC and receive INITB,
  582.    we should resend our INITB, but this could cause infinite echoing
  583.    of INITB on a long-latency line.  Rather than risk that, I have
  584.    implemented a fast drop-back procedure.  If we are sending INITB and
  585.    receive INITC, the other side has gotten ahead of us.  We immediately
  586.    fail and begin again with INITA.  For the other side, if we are
  587.    sending INITC and see INITA, we also immediately fail back to INITA.
  588.  
  589.    Unfortunately, this doesn't work for the other case, in which we
  590.    are sending INITB but the other side has not yet seen INITA.  As
  591.    far as I can see, if this happens we just have to wait until we
  592.    time out and resend INITA.  */
  593.  
  594. static boolean
  595. fgexchange_init (qdaemon, ictl, ival, piset)
  596.      struct sdaemon *qdaemon;
  597.      int ictl;
  598.      int ival;
  599.      int *piset;
  600. {
  601.   int i;
  602.  
  603.   /* The three-way handshake should be independent of who initializes
  604.      it, but it seems that some versions of uucico assume that the
  605.      caller sends first and the callee responds.  This only matters if
  606.      we are the callee and the first packet is garbled.  If we send a
  607.      packet, the other side will assume that we must have seen the
  608.      packet they sent and will never time out and send it again.
  609.      Therefore, if we are the callee we don't send a packet the first
  610.      time through the loop.  This can still fail, but should usually
  611.      work, and, after all, if the initialization packets are received
  612.      correctly there will be no problem no matter what we do.  */
  613.   for (i = 0; i < cGexchange_init_retries; i++)
  614.     {
  615.       long itime;
  616.       int ctimeout;
  617.  
  618.       if (qdaemon->fcaller || i > 0)
  619.     {
  620.       if (! fgsend_control (qdaemon, ictl, ival))
  621.         return FALSE;
  622.     }
  623.  
  624.       itime = ixsysdep_time ((long *) NULL);
  625.       ctimeout = cGexchange_init_timeout;
  626.  
  627.       do
  628.     {
  629.       long inewtime;
  630.  
  631.       /* We pass 0 as the retry count to fgwait_for_packet because
  632.          we want to handle retries here and because if it retried
  633.          it would send a packet, which would be bad.  */
  634.       if (! fgwait_for_packet (qdaemon, TRUE, ctimeout, 0))
  635.         break;
  636.  
  637.       if (CONTROL_TT (iGpacket_control) == CONTROL)
  638.         {
  639.           if (CONTROL_XXX (iGpacket_control) == ictl)
  640.         {
  641.           *piset = CONTROL_YYY (iGpacket_control);
  642.  
  643.           /* If we didn't already send our initialization
  644.              packet, send it now.  */
  645.           if (! qdaemon->fcaller && i == 0)
  646.             {
  647.               if (! fgsend_control (qdaemon, ictl, ival))
  648.             return FALSE;
  649.             }
  650.  
  651.           return TRUE;
  652.         }
  653.  
  654.           /* If the other side is farther along than we are,
  655.          we have lost a packet.  Fail immediately back to
  656.          INITA (but don't fail if we are already doing INITA,
  657.          since that would count against cStart_retries more
  658.          than it should).  */
  659.           if (CONTROL_XXX (iGpacket_control) < ictl && ictl != INITA)
  660.         return FALSE;
  661.  
  662.           /* If we are sending INITC and we receive an INITA, the other
  663.          side has failed back (we know this because we have
  664.          seen an INITB from them).  Fail back ourselves to
  665.          start the whole handshake over again.  */
  666.           if (CONTROL_XXX (iGpacket_control) == INITA && ictl == INITC)
  667.         return FALSE;
  668.  
  669.           /* As a special hack, if we are sending INITC and we
  670.          receive INITB, we update the segment size from the
  671.          packet.  This permits a second INITB to override the
  672.          first one.  It would be nice to do this in a cleaner
  673.          way.  */
  674.           if (CONTROL_XXX (iGpacket_control) == INITB && ictl == INITC)
  675.         iGremote_segsize = CONTROL_YYY (iGpacket_control);
  676.         }
  677.  
  678.       inewtime = ixsysdep_time ((long *) NULL);
  679.       ctimeout -= inewtime - itime;
  680.     }
  681.       while (ctimeout > 0);
  682.     }
  683.  
  684.   return FALSE;
  685. }
  686.  
  687. /* Shut down the protocol.  */
  688.  
  689. boolean
  690. fgshutdown (qdaemon)
  691.      struct sdaemon *qdaemon;
  692. {
  693.   (void) fgsend_control (qdaemon, CLOSE, 0);
  694.   (void) fgsend_control (qdaemon, CLOSE, 0);
  695.   (void) fginit_sendbuffers (FALSE);
  696.  
  697.   /* The count of sent packets may not be accurate, because some of
  698.      them may have not been sent yet if the connection failed in the
  699.      middle (the ones that counted for cGdelayed_packets).  I don't
  700.      think it's worth being precise.  */
  701.   ulog (LOG_NORMAL,
  702.     "Protocol '%c' packets: sent %ld, resent %ld, received %ld",
  703.     qdaemon->qproto->bname, cGsent_packets,
  704.     cGresent_packets - cGdelayed_packets, cGrec_packets);
  705.   if (cGbad_hdr != 0
  706.       || cGbad_checksum != 0
  707.       || cGbad_order != 0
  708.       || cGremote_rejects != 0
  709.       || cGremote_duprrs != 0)
  710.     ulog (LOG_NORMAL,
  711.       "Errors: header %ld, checksum %ld, order %ld, remote rejects %ld",
  712.       cGbad_hdr, cGbad_checksum, cGbad_order,
  713.       cGremote_duprrs + cGremote_rejects);
  714.  
  715.   /* Reset all the parameters to their default values, so that the
  716.      protocol parameters used for this connection do not affect the
  717.      next one.  */
  718.   iGrequest_winsize = IWINDOW;
  719.   iGrequest_packsize = IPACKSIZE;
  720.   cGstartup_retries = CSTARTUP_RETRIES;
  721.   cGexchange_init_timeout = CEXCHANGE_INIT_TIMEOUT;
  722.   cGexchange_init_retries = CEXCHANGE_INIT_RETRIES;
  723.   cGtimeout = CTIMEOUT;
  724.   cGretries = CRETRIES;
  725.   cGgarbage_data = CGARBAGE;
  726.   cGmax_errors = CERRORS;
  727.   cGerror_decay = CERROR_DECAY;
  728.   iGforced_remote_winsize = IREMOTE_WINDOW;
  729.   iGforced_remote_packsize = IREMOTE_PACKSIZE;
  730.   fGshort_packets = TRUE;
  731.  
  732.   return TRUE;
  733. }
  734.  
  735. /* Send a command string.  We send packets containing the string until
  736.    the entire string has been sent.  Each packet is full.  */
  737.  
  738. /*ARGSUSED*/
  739. boolean
  740. fgsendcmd (qdaemon, z, ilocal, iremote)
  741.      struct sdaemon *qdaemon;
  742.      const char *z;
  743.      int ilocal;
  744.      int iremote;
  745. {
  746.   size_t clen;
  747.   boolean fagain;
  748.  
  749.   DEBUG_MESSAGE1 (DEBUG_UUCP_PROTO, "fgsendcmd: Sending command \"%s\"", z);
  750.  
  751.   clen = strlen (z);
  752.  
  753.   do
  754.     {
  755.       char *zpacket;
  756.       size_t cdummy;
  757.  
  758.       zpacket = zggetspace (qdaemon, &cdummy);
  759.  
  760.       if (clen < iGremote_packsize)
  761.     {
  762.       size_t csize;
  763.  
  764.       /* If the remote packet size is larger than 64 (the default,
  765.          which may indicate an older UUCP package), try to fit
  766.          this command into a smaller packet.  We still always send
  767.          a complete packet, though.  */
  768.       if (iGremote_packsize <= 64 || ! fGshort_packets)
  769.         csize = iGremote_packsize;
  770.       else
  771.         {
  772.           csize = 32;
  773.           while (csize <= clen)
  774.         csize <<= 1;
  775.         }
  776.  
  777.       memcpy (zpacket, z, clen);
  778.       if (csize > clen)
  779.         bzero (zpacket + clen, csize - clen);
  780.       fagain = FALSE;
  781.  
  782.       if (! fgsenddata (qdaemon, zpacket, csize, 0, 0, (long) 0))
  783.         return FALSE;
  784.     }
  785.       else
  786.     {
  787.       memcpy (zpacket, z, iGremote_packsize);
  788.       z += iGremote_packsize;
  789.       clen -= iGremote_packsize;
  790.       fagain = TRUE;
  791.  
  792.       if (! fgsenddata (qdaemon, zpacket, iGremote_packsize,
  793.                 0, 0, (long) 0))
  794.         return FALSE;
  795.     }
  796.     }
  797.   while (fagain);
  798.  
  799.   return TRUE;
  800. }
  801.  
  802. /* We keep an array of buffers to retransmit as necessary.  Rather
  803.    than waste static space on large buffer sizes, we allocate the
  804.    buffers once we know how large the other system expects them to be.
  805.    The sequence numbers used in the 'g' protocol are only three bits
  806.    long, so we allocate eight buffers and maintain a correspondence
  807.    between buffer index and sequence number.  This always wastes some
  808.    buffer space, but it's easy to implement.
  809.  
  810.    We leave room at the front of the buffer for the frame header and
  811.    two additional bytes.  The two extra bytes are used for short
  812.    packets, which essentially use a longer header and shorter data.
  813.    We do this to avoid moving the data.  We zero out any unused bytes
  814.    before the frame, so we can locate the real header given a buffer
  815.    by finding the first non-zero byte (which will be one of the first
  816.    three bytes in the buffer).  */
  817.  
  818. #define CSENDBUFFERS (CMAXWINDOW + 1)
  819.  
  820. static char *azGsendbuffers[CSENDBUFFERS];
  821.  
  822. static boolean
  823. fginit_sendbuffers (fallocate)
  824.      boolean fallocate;
  825. {
  826.   int i;
  827.  
  828.   /* Free up any remaining old buffers.  */
  829.   for (i = 0; i < CSENDBUFFERS; i++)
  830.     {
  831.       xfree ((pointer) azGsendbuffers[i]);
  832.       if (fallocate)
  833.     {
  834.       azGsendbuffers[i] = (char *) malloc (CFRAMELEN + 2
  835.                            + iGremote_packsize);
  836.       if (azGsendbuffers[i] == NULL)
  837.         return FALSE;
  838.  
  839.       /* This bzero might not seem necessary, since before we send
  840.          out each packet we zero out any non-data bytes.  However,
  841.          if we receive an SRJ at the start of the conversation, we
  842.          will send out the packet before it has been set to
  843.          anything, thus sending the contents of our heap.  We
  844.          avoid this by using bzero.  */
  845.       bzero (azGsendbuffers[i], CFRAMELEN + 2 + iGremote_packsize);
  846.     }
  847.       else
  848.     azGsendbuffers[i] = NULL;
  849.     }
  850.   return TRUE;
  851. }
  852.  
  853. /* Allocate a packet to send out.  The return value of this function
  854.    must be filled in and passed to fgsenddata, or discarded.  This
  855.    will ensure that the buffers and iGsendseq stay in synch.  Set
  856.    *pclen to the amount of data to place in the buffer.  */
  857.  
  858. /*ARGSUSED*/
  859. char *
  860. zggetspace (qdaemon, pclen)
  861.      struct sdaemon *qdaemon;
  862.      size_t *pclen;
  863. {
  864.   *pclen = iGremote_packsize;
  865.   return azGsendbuffers[iGsendseq] + CFRAMELEN + 2;
  866. }
  867.  
  868. /* Send out a data packet.  This computes the checksum, sets up the
  869.    header, and sends the packet out.  The argument zdata should point
  870.    to the return value of zggetspace.  */
  871.  
  872. /*ARGSIGNORED*/
  873. boolean
  874. fgsenddata (qdaemon, zdata, cdata, ilocal, iremote, ipos)
  875.      struct sdaemon *qdaemon;
  876.      char *zdata;
  877.      size_t cdata;
  878.      int ilocal;
  879.      int iremote;
  880.      long ipos;
  881. {
  882.   char *z;
  883.   int itt, iseg;
  884.   size_t csize;
  885.   int iclr1, iclr2;
  886.   unsigned short icheck;
  887.  
  888.   /* Set the initial length bytes.  See the description at the definition
  889.      of SHORTDATA, above.  */
  890.   itt = DATA;
  891.   csize = iGremote_packsize;
  892.   iseg = iGremote_segsize + 1;
  893.  
  894. #if DEBUG > 0
  895.   if (cdata > csize)
  896.     ulog (LOG_FATAL, "fgsend_packet: Packet size too large");
  897. #endif
  898.  
  899.   iclr1 = -1;
  900.   iclr2 = -2;
  901.   if (cdata < csize)
  902.     {
  903.       /* If the remote packet size is larger than 64, the default, we
  904.      can assume they can handle a smaller packet as well, which
  905.      will be more efficient to send.  */
  906.       if (iGremote_packsize > 64 && fGshort_packets)
  907.     {
  908.       /* The packet size is 1 << (iseg + 4).  */
  909.       iseg = 1;
  910.       csize = 32;
  911.       while (csize < cdata)
  912.         {
  913.           csize <<= 1;
  914.           ++iseg;
  915.         }
  916.     }
  917.  
  918.       if (csize != cdata)
  919.     {
  920.       size_t cshort;
  921.  
  922.       /* We have to add bytes which indicate how short the packet
  923.          is.  We do this by pushing the header backward, which we
  924.          can do because we allocated two extra bytes for this
  925.          purpose.  */
  926.       iclr2 = 0;
  927.       itt = SHORTDATA;
  928.       cshort = csize - cdata;
  929.       if (cshort <= 127)
  930.         {
  931.           --zdata;
  932.           zdata[0] = (char) cshort;
  933.           zdata[-1] = '\0';
  934.           if (cshort > 1)
  935.         bzero (zdata + cdata + 1, cshort - 1);
  936.         }
  937.       else
  938.         {
  939.           zdata -= 2;
  940.           zdata[0] = (char) (0x80 | (cshort & 0x7f));
  941.           zdata[1] = (char) (cshort >> 7);
  942.           bzero (zdata + cdata + 2, cshort - 2);
  943.           iclr1 = 0;
  944.         }
  945.     }
  946.     }
  947.  
  948.   z = zdata - CFRAMELEN;
  949.  
  950.   /* Zero out the preceding bytes, in case the last time this buffer
  951.      was used those bytes were used.  We need to zero out the initial
  952.      bytes so that we can find the true start of the packet in
  953.      zgadjust_ack.  */
  954.   z[iclr1] = '\0';
  955.   z[iclr2] = '\0';
  956.  
  957.   z[IFRAME_DLE] = DLE;
  958.   z[IFRAME_K] = (char) iseg;
  959.  
  960.   icheck = (unsigned short) igchecksum (zdata, csize);
  961.  
  962.   /* We're just about ready to go.  Wait until there is room in the
  963.      receiver's window for us to send the packet.  We do this now so
  964.      that we send the correct value for the last packet received.
  965.      Note that if iGsendseq == iGremote_ack, this means that the
  966.      sequence numbers are actually 8 apart, since the packet could not
  967.      have been acknowledged before it was sent; this can happen when
  968.      the window size is 7.  */
  969.   while (iGsendseq == iGremote_ack
  970.      || CSEQDIFF (iGsendseq, iGremote_ack) > iGremote_winsize)
  971.     {
  972.       if (! fgwait_for_packet (qdaemon, TRUE, cGtimeout, cGretries))
  973.     return FALSE;
  974.     }
  975.  
  976.   /* Ack all packets up to the next one, since the UUCP protocol
  977.      requires that all packets be acked in order.  */
  978.   while (CSEQDIFF (iGrecseq, iGlocal_ack) > 1)
  979.     {
  980.       iGlocal_ack = INEXTSEQ (iGlocal_ack);
  981.       if (! fgsend_control (qdaemon, RR, iGlocal_ack))
  982.     return FALSE;
  983.     }
  984.   iGlocal_ack = iGrecseq;
  985.  
  986.   z[IFRAME_CONTROL] = (char) ((itt << 6) | (iGsendseq << 3) | iGrecseq);
  987.  
  988.   iGsendseq = INEXTSEQ (iGsendseq);
  989.  
  990.   icheck = ((unsigned short)
  991.         ((0xaaaa - (icheck ^ (z[IFRAME_CONTROL] & 0xff))) & 0xffff));
  992.   z[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
  993.   z[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
  994.  
  995.   z[IFRAME_XOR] = (char) (z[IFRAME_K] ^ z[IFRAME_CHECKLOW]
  996.               ^ z[IFRAME_CHECKHIGH] ^ z[IFRAME_CONTROL]);
  997.  
  998.   /* If we're waiting for acks of retransmitted packets, then don't
  999.      send this packet yet.  The other side may not be ready for it
  1000.      yet.  Instead, code in fggot_ack will send the outstanding
  1001.      packets when an ack is received.  */
  1002.   ++cGsent_packets;
  1003.  
  1004.   if (iGretransmit_seq != -1)
  1005.     {
  1006.       ++cGdelayed_packets;
  1007.       return TRUE;
  1008.     }
  1009.  
  1010.   DEBUG_MESSAGE2 (DEBUG_PROTO,
  1011.           "fgsenddata: Sending packet %d (%d bytes)",
  1012.           CONTROL_XXX (z[IFRAME_CONTROL]), cdata);
  1013.  
  1014.   return fsend_data (qdaemon->qconn, z, CFRAMELEN + csize, TRUE);
  1015. }
  1016.  
  1017. /* Recompute the control byte and checksum of a packet so that it
  1018.    includes the correct packet acknowledgement.  This is called when a
  1019.    packet is retransmitted to make sure the retransmission does not
  1020.    confuse the other side.  It returns a pointer to the start of the
  1021.    packet, skipping the bytes that may be unused at the start of
  1022.    azGsendbuffers[iseq].  */
  1023.  
  1024. static char *
  1025. zgadjust_ack (iseq)
  1026.      int iseq;
  1027. {
  1028.   register char *z;
  1029.   unsigned short icheck;
  1030.  
  1031.   z = azGsendbuffers[iseq];
  1032.   if (*z == '\0')
  1033.     ++z;
  1034.   if (*z == '\0')
  1035.     ++z;
  1036.  
  1037.   /* If the received packet number is the same, there is nothing
  1038.      to do.  */
  1039.   if (CONTROL_YYY (z[IFRAME_CONTROL]) == iGrecseq)
  1040.     return z;
  1041.  
  1042.   /* Get the old checksum.  */
  1043.   icheck = (unsigned short) (((z[IFRAME_CHECKHIGH] & 0xff) << 8)
  1044.                  | (z[IFRAME_CHECKLOW] & 0xff));
  1045.   icheck = ((unsigned short)
  1046.         (((0xaaaa - icheck) ^ (z[IFRAME_CONTROL] & 0xff)) & 0xffff));
  1047.  
  1048.   /* Update the control byte.  */
  1049.   z[IFRAME_CONTROL] = (char) ((z[IFRAME_CONTROL] &~ 07) | iGrecseq);
  1050.  
  1051.   /* Create the new checksum.  */
  1052.   icheck = ((unsigned short)
  1053.         ((0xaaaa - (icheck ^ (z[IFRAME_CONTROL] & 0xff))) & 0xffff));
  1054.   z[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
  1055.   z[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
  1056.  
  1057.   /* Update the XOR byte.  */
  1058.   z[IFRAME_XOR] = (char) (z[IFRAME_K] ^ z[IFRAME_CHECKLOW]
  1059.               ^ z[IFRAME_CHECKHIGH] ^ z[IFRAME_CONTROL]);
  1060.  
  1061.   return z;
  1062. }
  1063.  
  1064. /* Send a control packet.  These are fairly simple to construct.  It
  1065.    seems reasonable to me that we should be able to send a control
  1066.    packet at any time, even if the receive window is closed.  In
  1067.    particular, we don't want to delay when sending a CLOSE control
  1068.    message.  If I'm wrong, it can be changed easily enough.  */
  1069.  
  1070. static boolean
  1071. fgsend_control (qdaemon, ixxx, iyyy)
  1072.      struct sdaemon *qdaemon;
  1073.      int ixxx;
  1074.      int iyyy;
  1075. {
  1076.   char ab[CFRAMELEN];
  1077.   int ictl;
  1078.   unsigned short icheck;
  1079.  
  1080. #if DEBUG > 1
  1081.   if (FDEBUGGING (DEBUG_PROTO) ||
  1082.       (FDEBUGGING (DEBUG_ABNORMAL) && ixxx != RR))
  1083.     ulog (LOG_DEBUG, "fgsend_control: Sending control %s %d",
  1084.       azGcontrol[ixxx], iyyy);
  1085. #endif
  1086.  
  1087.   ab[IFRAME_DLE] = DLE;
  1088.   ab[IFRAME_K] = KCONTROL;
  1089.  
  1090.   ictl = (CONTROL << 6) | (ixxx << 3) | iyyy;
  1091.   icheck = (unsigned short) (0xaaaa - ictl);
  1092.   ab[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
  1093.   ab[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
  1094.  
  1095.   ab[IFRAME_CONTROL] = (char) ictl;
  1096.  
  1097.   ab[IFRAME_XOR] = (char) (ab[IFRAME_K] ^ ab[IFRAME_CHECKLOW]
  1098.                ^ ab[IFRAME_CHECKHIGH] ^ ab[IFRAME_CONTROL]);
  1099.  
  1100.   return fsend_data (qdaemon->qconn, ab, (size_t) CFRAMELEN, TRUE);
  1101. }
  1102.  
  1103. /* Wait for data to come in.  This continues processing until a
  1104.    complete file or command has been received.  */
  1105.  
  1106. boolean
  1107. fgwait (qdaemon)
  1108.      struct sdaemon *qdaemon;
  1109. {
  1110.   return fgwait_for_packet (qdaemon, FALSE, cGtimeout, cGretries);
  1111. }
  1112.  
  1113. /* Get a packet.  This is called when we have nothing to send, but
  1114.    want to wait for a packet to come in.  If freturncontrol is TRUE,
  1115.    this will return after getting any control packet.  Otherwise, it
  1116.    will continue to receive packets until a complete file or a
  1117.    complete command has been received.  The timeout and the number of
  1118.    retries are specified as arguments.  The function returns FALSE if
  1119.    an error occurs or if cretries timeouts of ctimeout seconds were
  1120.    exceeded.  */
  1121.  
  1122. static boolean
  1123. fgwait_for_packet (qdaemon, freturncontrol, ctimeout, cretries)
  1124.      struct sdaemon *qdaemon;
  1125.      boolean freturncontrol;
  1126.      int ctimeout;
  1127.      int cretries;
  1128. {
  1129.   int ctimeouts;
  1130.   int cgarbage;
  1131.   int cshort;
  1132.  
  1133.   ctimeouts = 0;
  1134.   cgarbage = 0;
  1135.   cshort = 0;
  1136.  
  1137.   while (TRUE)
  1138.     {
  1139.       boolean fexit;
  1140.       size_t cneed;
  1141.       boolean ffound;
  1142.       size_t crec;
  1143.   
  1144.       if (! fgprocess_data (qdaemon, TRUE, freturncontrol, &fexit,
  1145.                 &cneed, &ffound))
  1146.     return FALSE;
  1147.  
  1148.       if (fexit)
  1149.     return TRUE;
  1150.  
  1151.       DEBUG_MESSAGE1 (DEBUG_PROTO,
  1152.               "fgwait_for_packet: Need %lu bytes",
  1153.               (unsigned long) cneed);
  1154.  
  1155.       if (ffound)
  1156.     {
  1157.       ctimeouts = 0;
  1158.       cgarbage = 0;
  1159.     }
  1160.       else
  1161.     {
  1162.       if (cgarbage > cGgarbage_data)
  1163.         {
  1164.           ulog (LOG_ERROR, "Too much unrecognized data");
  1165.           return FALSE;
  1166.         }
  1167.     }
  1168.  
  1169.       if (! freceive_data (qdaemon->qconn, cneed, &crec, ctimeout, TRUE))
  1170.     return FALSE;
  1171.  
  1172.       cgarbage += crec;
  1173.  
  1174.       if (crec != 0)
  1175.     {
  1176.       /* If we don't get enough data twice in a row, we may have
  1177.          dropped some data and still be looking for the end of a
  1178.          large packet.  Incrementing iPrecstart will force
  1179.          fgprocess_data to skip that packet and look through the
  1180.          rest of the data.  In some situations, this will be a
  1181.          mistake.  */
  1182.       if (crec >= cneed)
  1183.         cshort = 0;
  1184.       else
  1185.         {
  1186.           ++cshort;
  1187.           if (cshort > 1)
  1188.         {
  1189.           iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
  1190.           cshort = 0;
  1191.         }
  1192.         }
  1193.     }
  1194.       else
  1195.     {
  1196.       /* The read timed out.  If we have an unacknowledged packet,
  1197.          send it again.  Otherwise, send an RJ with the last
  1198.          packet we received correctly.  */
  1199.       ++ctimeouts;
  1200.       if (ctimeouts > cretries)
  1201.         {
  1202.           if (cretries > 0)
  1203.         ulog (LOG_ERROR, "Timed out waiting for packet");
  1204.           return FALSE;
  1205.         }
  1206.  
  1207.       if (INEXTSEQ (iGremote_ack) != iGsendseq)
  1208.         {
  1209.           int inext;
  1210.           char *zsend;
  1211.  
  1212.           inext = INEXTSEQ (iGremote_ack);
  1213.  
  1214.           DEBUG_MESSAGE1 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1215.                   "fgwait_for_packet: Resending packet %d",
  1216.                   inext);
  1217.  
  1218.           ++cGresent_packets;
  1219.           zsend = zgadjust_ack (inext);
  1220.           if (! fsend_data (qdaemon->qconn, zsend,
  1221.                 CFRAMELEN + CPACKLEN (zsend), TRUE))
  1222.         return FALSE;
  1223.           iGretransmit_seq = inext;
  1224.         }
  1225.       else
  1226.         {
  1227.           /* Send all pending acks first, to avoid confusing
  1228.          the other side.  */
  1229.           if (iGlocal_ack != iGrecseq)
  1230.         {
  1231.           if (! fgsend_acks (qdaemon))
  1232.             return FALSE;
  1233.         }
  1234.           if (! fgsend_control (qdaemon, RJ, iGrecseq))
  1235.         return FALSE;
  1236.         }
  1237.     }
  1238.     }
  1239. }
  1240.  
  1241. /* Send acks for all packets we haven't acked yet.  */
  1242.  
  1243. static boolean
  1244. fgsend_acks (qdaemon)
  1245.      struct sdaemon *qdaemon;
  1246. {
  1247.   while (iGlocal_ack != iGrecseq)
  1248.     {
  1249.       iGlocal_ack = INEXTSEQ (iGlocal_ack);
  1250.       if (! fgsend_control (qdaemon, RR, iGlocal_ack))
  1251.     return FALSE;
  1252.     }
  1253.   return TRUE;
  1254. }
  1255.  
  1256. /* Handle an ack of a packet.  According to Hanrahan's paper, this
  1257.    acknowledges all previous packets.  If this is an ack for a
  1258.    retransmitted packet, continue by resending up to two more packets
  1259.    following the retransmitted one.  This should recover quickly from
  1260.    a line glitch, while avoiding the problem of continual
  1261.    retransmission.  */
  1262.  
  1263. static boolean
  1264. fggot_ack (qdaemon, iack)
  1265.      struct sdaemon *qdaemon;
  1266.      int iack;
  1267. {
  1268.   int inext;
  1269.   char *zsend;
  1270.  
  1271.   /* We only decrement the error level if we are not retransmitting
  1272.      packets.  We want to catch a sudden downgrade in line quality as
  1273.      fast as possible.  */
  1274.   if (cGerror_level > 0
  1275.       && iGretransmit_seq == -1
  1276.       && cGsent_packets % cGerror_decay == 0)
  1277.     --cGerror_level;
  1278.   cGexpect_bad_order = 0;
  1279.  
  1280.   /* Each time packet 0 is acknowledged, we call uwindow_acked since a
  1281.      new window has been acked.  */
  1282.   if (iack < iGremote_ack)
  1283.     uwindow_acked (qdaemon, FALSE);
  1284.  
  1285.   iGremote_ack = iack;
  1286.  
  1287.   if (iGretransmit_seq == -1)
  1288.     return TRUE;
  1289.  
  1290.   inext = INEXTSEQ (iGretransmit_seq);
  1291.   if (inext == iGsendseq)
  1292.     iGretransmit_seq = -1;
  1293.   else
  1294.     {
  1295.       DEBUG_MESSAGE1 (DEBUG_PROTO,
  1296.               "fggot_ack: Sending packet %d", inext);
  1297.  
  1298.       ++cGresent_packets;
  1299.       zsend = zgadjust_ack (inext);
  1300.       if (! fsend_data (qdaemon->qconn, zsend, CFRAMELEN + CPACKLEN (zsend),
  1301.             TRUE))
  1302.     return FALSE;
  1303.       inext = INEXTSEQ (inext);
  1304.       if (inext == iGsendseq)
  1305.     iGretransmit_seq = -1;
  1306.       else
  1307.     {
  1308.       DEBUG_MESSAGE1 (DEBUG_PROTO,
  1309.               "fggot_ack: Sending packet %d", inext);
  1310.  
  1311.       ++cGresent_packets;
  1312.       zsend = zgadjust_ack (inext);
  1313.       if (! fsend_data (qdaemon->qconn, zsend,
  1314.                 CFRAMELEN + CPACKLEN (zsend), TRUE))
  1315.         return FALSE;
  1316.       iGretransmit_seq = inext;
  1317.     }
  1318.     }
  1319.  
  1320.   return TRUE;
  1321. }
  1322.  
  1323. /* See if we've received more than the permitted number of errors.  If
  1324.    we receive a bad packet, we can expect a window full (less one) of
  1325.    out of order packets to follow, so we discount cGbad_order
  1326.    accordingly.  */
  1327.  
  1328. static boolean
  1329. fgcheck_errors (qdaemon)
  1330.      struct sdaemon *qdaemon;
  1331. {
  1332.   if (cGerror_level > cGmax_errors && cGmax_errors >= 0)
  1333.     {
  1334.       ulog (LOG_ERROR, "Too many '%c' protocol errors",
  1335.         qdaemon->qproto->bname);
  1336.       return FALSE;
  1337.     }
  1338.  
  1339.   return TRUE;
  1340. }
  1341.  
  1342. /* Process the receive buffer into a data packet, if possible.  All
  1343.    control packets are handled here.  When a data packet is received,
  1344.    fgprocess_data calls fgot_data with the data; if that sets its
  1345.    pfexit argument to TRUE fgprocess_data will set *pfexit to TRUE and
  1346.    return TRUE.  Also, if the freturncontrol argument is TRUE
  1347.    fgprocess_data will set *pfexit to TRUE and return TRUE.  Otherwise
  1348.    fgprocess_data will continue trying to process data.  If some error
  1349.    occurs, fgprocess_data will return FALSE.  If there is not enough
  1350.    data to form a complete packet, then *pfexit will be set to FALSE,
  1351.    *pcneed will be set to the number of bytes needed to form a
  1352.    complete packet (unless pcneed is NULL) and fgprocess_data will
  1353.    return TRUE.  If this function found a data packet, and pffound is
  1354.    not NULL, it will set *pffound to TRUE; this can be used to tell
  1355.    valid data from an endless stream of garbage and control packets.
  1356.    If fdoacks is TRUE, received packets will be acknowledged;
  1357.    otherwise they must be acknowledged later.  */
  1358.  
  1359. static boolean
  1360. fgprocess_data (qdaemon, fdoacks, freturncontrol, pfexit, pcneed, pffound)
  1361.      struct sdaemon *qdaemon;
  1362.      boolean fdoacks;
  1363.      boolean freturncontrol;
  1364.      boolean *pfexit;
  1365.      size_t *pcneed;
  1366.      boolean *pffound;
  1367. {
  1368.   *pfexit = FALSE;
  1369.   if (pffound != NULL)
  1370.     *pffound = FALSE;
  1371.  
  1372.   while (iPrecstart != iPrecend)
  1373.     {
  1374.       char ab[CFRAMELEN];
  1375.       int i, iget, cwant;
  1376.       unsigned short ihdrcheck, idatcheck;
  1377.       const char *zfirst, *zsecond;
  1378.       int cfirst, csecond;
  1379.       boolean fduprr;
  1380.  
  1381.       /* Look for the DLE which must start a packet.  */
  1382.       if (abPrecbuf[iPrecstart] != DLE)
  1383.     {
  1384.       char *zdle;
  1385.  
  1386.       cfirst = iPrecend - iPrecstart;
  1387.       if (cfirst < 0)
  1388.         cfirst = CRECBUFLEN - iPrecstart;
  1389.  
  1390.       zdle = memchr (abPrecbuf + iPrecstart, DLE, (size_t) cfirst);
  1391.  
  1392.       if (zdle == NULL)
  1393.         {
  1394.           iPrecstart = (iPrecstart + cfirst) % CRECBUFLEN;
  1395.           continue;
  1396.         }
  1397.  
  1398.       /* We don't need % CRECBUFLEN here because zdle - (abPrecbuf
  1399.          + iPrecstart) < cfirst <= CRECBUFLEN - iPrecstart.  */
  1400.       iPrecstart += zdle - (abPrecbuf + iPrecstart);
  1401.     }
  1402.  
  1403.       /* Get the first six bytes into ab.  */
  1404.       for (i = 0, iget = iPrecstart;
  1405.        i < CFRAMELEN && iget != iPrecend;
  1406.        i++, iget = (iget + 1) % CRECBUFLEN)
  1407.     ab[i] = abPrecbuf[iget];
  1408.  
  1409.       /* If there aren't six bytes, there is no packet.  */
  1410.       if (i < CFRAMELEN)
  1411.     {
  1412.       if (pcneed != NULL)
  1413.         *pcneed = CFRAMELEN - i;
  1414.       return TRUE;
  1415.     }
  1416.  
  1417.       /* Make sure these six bytes start a packet.  The check on
  1418.      IFRAME_DLE is basically a debugging check, since the above
  1419.      code should have ensured that it will never fail.  If this is
  1420.      not the start of a packet, bump iPrecstart and loop around to
  1421.      look for another DLE.  */
  1422.       if (ab[IFRAME_DLE] != DLE
  1423.       || ab[IFRAME_K] < 1
  1424.       || ab[IFRAME_K] > 9
  1425.       || ab[IFRAME_XOR] != (ab[IFRAME_K] ^ ab[IFRAME_CHECKLOW]
  1426.                 ^ ab[IFRAME_CHECKHIGH] ^ ab[IFRAME_CONTROL])
  1427.       || CONTROL_TT (ab[IFRAME_CONTROL]) == ALTCHAN)
  1428.     {
  1429.       ++cGbad_hdr;
  1430.       ++cGerror_level;
  1431.  
  1432.       DEBUG_MESSAGE4 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1433.               "fgprocess_data: Bad header: K %d TT %d XOR byte %d calc %d",
  1434.               ab[IFRAME_K] & 0xff,
  1435.               CONTROL_TT (ab[IFRAME_CONTROL]),
  1436.               ab[IFRAME_XOR] & 0xff,
  1437.               (ab[IFRAME_K]
  1438.                ^ ab[IFRAME_CHECKLOW]
  1439.                ^ ab[IFRAME_CHECKHIGH]
  1440.                ^ ab[IFRAME_CONTROL]) & 0xff);
  1441.  
  1442.       if (! fgcheck_errors (qdaemon))
  1443.         return FALSE;
  1444.  
  1445.       iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
  1446.       continue;
  1447.     }
  1448.  
  1449.       /* The zfirst and cfirst pair point to the first set of data for
  1450.      this packet; the zsecond and csecond point to the second set,
  1451.      in case the packet wraps around the end of the buffer.  */
  1452.       zfirst = abPrecbuf + iPrecstart + CFRAMELEN;
  1453.       cfirst = 0;
  1454.       zsecond = NULL;
  1455.       csecond = 0;
  1456.  
  1457.       if (ab[IFRAME_K] == KCONTROL)
  1458.     {
  1459.       /* This is a control packet.  It should not have any data.  */
  1460.       if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
  1461.         {
  1462.           ++cGbad_hdr;
  1463.           ++cGerror_level;
  1464.  
  1465.           DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1466.                   "fgprocess_data: Bad header: control packet with data");
  1467.  
  1468.           if (! fgcheck_errors (qdaemon))
  1469.         return FALSE;
  1470.  
  1471.           iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
  1472.           continue;
  1473.         }
  1474.  
  1475.       idatcheck = (unsigned short) (0xaaaa - ab[IFRAME_CONTROL]);
  1476.       cwant = 0;
  1477.     }
  1478.       else
  1479.     {
  1480.       int cinbuf;
  1481.       unsigned short icheck;
  1482.  
  1483.       /* This is a data packet.  It should not be type CONTROL.  */
  1484.       if (CONTROL_TT (ab[IFRAME_CONTROL]) == CONTROL)
  1485.         {
  1486.           ++cGbad_hdr;
  1487.           ++cGerror_level;
  1488.  
  1489.           DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1490.                   "fgprocess_data: Bad header: data packet is type CONTROL");
  1491.  
  1492.           if (! fgcheck_errors (qdaemon))
  1493.         return FALSE;
  1494.  
  1495.           iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
  1496.           continue;
  1497.         }
  1498.  
  1499.       cinbuf = iPrecend - iPrecstart;
  1500.       if (cinbuf < 0)
  1501.         cinbuf += CRECBUFLEN;
  1502.       cinbuf -= CFRAMELEN;
  1503.  
  1504.       /* Make sure we have enough data.  If we don't, wait for
  1505.          more.  */         
  1506.  
  1507.       cwant = (int) CPACKLEN (ab);
  1508.       if (cinbuf < cwant)
  1509.         {
  1510.           if (pcneed != NULL)
  1511.         *pcneed = cwant - cinbuf;
  1512.           return TRUE;
  1513.         }
  1514.       
  1515.       /* Set up the data pointers and compute the checksum.  */
  1516.       if (iPrecend >= iPrecstart)
  1517.         cfirst = cwant;
  1518.       else
  1519.         {
  1520.           cfirst = CRECBUFLEN - (iPrecstart + CFRAMELEN);
  1521.           if (cfirst >= cwant)
  1522.         cfirst = cwant;
  1523.           else if (cfirst > 0)
  1524.         {
  1525.           zsecond = abPrecbuf;
  1526.           csecond = cwant - cfirst;
  1527.         }
  1528.           else
  1529.         {
  1530.           /* Here cfirst is non-positive, so subtracting from
  1531.              abPrecbuf will actually skip the appropriate number
  1532.              of bytes at the start of abPrecbuf.  */
  1533.           zfirst = abPrecbuf - cfirst;
  1534.           cfirst = cwant;
  1535.         }
  1536.         }
  1537.  
  1538.       if (csecond == 0)
  1539.         icheck = (unsigned short) igchecksum (zfirst, (size_t) cfirst);
  1540.       else
  1541.         icheck = (unsigned short) igchecksum2 (zfirst, (size_t) cfirst,
  1542.                            zsecond,
  1543.                            (size_t) csecond);
  1544.  
  1545.       idatcheck = ((unsigned short)
  1546.                (((0xaaaa - (icheck ^ (ab[IFRAME_CONTROL] & 0xff)))
  1547.              & 0xffff)));
  1548.     }
  1549.       
  1550.       ihdrcheck = (unsigned short) (((ab[IFRAME_CHECKHIGH] & 0xff) << 8)
  1551.                     | (ab[IFRAME_CHECKLOW] & 0xff));
  1552.  
  1553.       if (ihdrcheck != idatcheck)
  1554.     {
  1555.       DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1556.               "fgprocess_data: Bad checksum: header 0x%x, data 0x%x",
  1557.               ihdrcheck, idatcheck);
  1558.  
  1559.       ++cGbad_checksum;
  1560.       ++cGerror_level;
  1561.  
  1562.       if (! fgcheck_errors (qdaemon))
  1563.         return FALSE;
  1564.  
  1565.       /* If the checksum failed for a data packet, then if it was
  1566.          the one we were expecting send an RJ, otherwise ignore
  1567.          it.  Previously if this code got the wrong packet number
  1568.          it would send an RR, but that may confuse some Telebit
  1569.          modems and it doesn't help in any case since the receiver
  1570.          will probably just ignore the RR as a duplicate (that's
  1571.          basically what this code does).  If we totally missed the
  1572.          packet we will time out and send an RJ in the function
  1573.          fgwait_for_packet above.  */
  1574.       if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
  1575.         {
  1576.           /* Make sure we've acked everything up to this point.  */
  1577.           if (iGrecseq != iGlocal_ack)
  1578.         {
  1579.           if (! fgsend_acks (qdaemon))
  1580.             return FALSE;
  1581.         }
  1582.  
  1583.           /* If this is the packet we wanted, tell the sender that
  1584.          it failed.  */
  1585.           if (CONTROL_XXX (ab[IFRAME_CONTROL]) == INEXTSEQ (iGrecseq))
  1586.         {
  1587.           if (! fgsend_control (qdaemon, RJ, iGrecseq))
  1588.             return FALSE;
  1589.           cGexpect_bad_order += iGrequest_winsize - 1;
  1590.         }
  1591.         }
  1592.  
  1593.       /* We can't skip the packet data after this, because if we
  1594.          have lost incoming bytes the next DLE will be somewhere
  1595.          in what we thought was the packet data.  */
  1596.       iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
  1597.       continue;
  1598.     }
  1599.  
  1600.       /* We have a packet; remove the processed bytes from the receive
  1601.      buffer.  */
  1602.       iPrecstart = (iPrecstart + cwant + CFRAMELEN) % CRECBUFLEN;
  1603.  
  1604.       /* Store the control byte for the handshake routines.  */
  1605.       iGpacket_control = ab[IFRAME_CONTROL] & 0xff;
  1606.  
  1607.       /* Annoyingly, some UUCP packages appear to send an RR packet
  1608.      rather than an RJ packet when they want a packet to be
  1609.      resent.  If we get a duplicate RR and we've never seen an RJ,
  1610.      we treat the RR as an RJ.  */
  1611.       fduprr = FALSE;
  1612.       if (cGremote_rejects == 0
  1613.       && CONTROL_TT (ab[IFRAME_CONTROL]) == CONTROL
  1614.       && CONTROL_XXX (ab[IFRAME_CONTROL]) == RR
  1615.       && iGremote_ack == CONTROL_YYY (ab[IFRAME_CONTROL])
  1616.       && INEXTSEQ (iGremote_ack) != iGsendseq
  1617.       && iGretransmit_seq == -1)
  1618.     {
  1619.       DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1620.               "fgprocess_data: Treating duplicate RR as RJ");
  1621.       fduprr = TRUE;
  1622.     }
  1623.  
  1624.       /* Update the received sequence number from the yyy field of a
  1625.      data packet (if it is the one we are expecting) or an RR
  1626.      control packet.  If we've been delaying sending packets until
  1627.      we received an ack, this may send out some packets.  */
  1628.       if ((CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL
  1629.        && CONTROL_XXX (ab[IFRAME_CONTROL]) == INEXTSEQ (iGrecseq))
  1630.       || (CONTROL_XXX (ab[IFRAME_CONTROL]) == RR && ! fduprr))
  1631.     {
  1632.       if (! fggot_ack (qdaemon, CONTROL_YYY (ab[IFRAME_CONTROL])))
  1633.         return FALSE;
  1634.     }
  1635.  
  1636.       /* If this isn't a control message, make sure we have received
  1637.      the expected packet sequence number, acknowledge the packet
  1638.      if it's the right one, and process the data.  */
  1639.       if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
  1640.     {
  1641.       if (CONTROL_XXX (ab[IFRAME_CONTROL]) != INEXTSEQ (iGrecseq))
  1642.         {
  1643.           /* We got the wrong packet number.  */
  1644.           DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1645.                   "fgprocess_data: Got packet %d; expected %d",
  1646.                   CONTROL_XXX (ab[IFRAME_CONTROL]),
  1647.                   INEXTSEQ (iGrecseq));
  1648.  
  1649.           if (cGexpect_bad_order > 0)
  1650.         --cGexpect_bad_order;
  1651.           else
  1652.         {
  1653.           ++cGbad_order;
  1654.           ++cGerror_level;
  1655.           if (! fgcheck_errors (qdaemon))
  1656.             return FALSE;
  1657.         }
  1658.  
  1659.           /* This code used to send an RR to encourage the other
  1660.          side to get back in synch, but that may confuse some
  1661.          Telebit modems and does little good in any case,
  1662.          since the other side will probably just ignore it
  1663.          anyhow (that's what this code does).  */
  1664.           continue;
  1665.         }
  1666.  
  1667.       /* We got the packet we expected.  */
  1668.       ++cGrec_packets;
  1669.       if (cGerror_level > 0
  1670.           && cGrec_packets % cGerror_decay == 0)
  1671.         --cGerror_level;
  1672.       cGexpect_bad_order = 0;
  1673.  
  1674.       iGrecseq = INEXTSEQ (iGrecseq);
  1675.  
  1676.       DEBUG_MESSAGE1 (DEBUG_PROTO,
  1677.               "fgprocess_data: Got packet %d", iGrecseq);
  1678.  
  1679.       /* Tell the caller that we found something.  */
  1680.       if (pffound != NULL)
  1681.         *pffound = TRUE;
  1682.  
  1683.       /* If we are supposed to do acknowledgements here, send back
  1684.          an RR packet.  */
  1685.       if (fdoacks)
  1686.         {
  1687.           if (! fgsend_acks (qdaemon))
  1688.         return FALSE;
  1689.         }
  1690.  
  1691.       /* If this is a short data packet, adjust the data pointers
  1692.          and lengths.  */
  1693.       if (CONTROL_TT (ab[IFRAME_CONTROL]) == SHORTDATA)
  1694.         {
  1695.           int cshort, cmove;
  1696.  
  1697.           if ((zfirst[0] & 0x80) == 0)
  1698.         {
  1699.           cshort = zfirst[0] & 0xff;
  1700.           cmove = 1;
  1701.         }
  1702.           else
  1703.         {
  1704.           int cbyte2;
  1705.  
  1706.           if (cfirst > 1)
  1707.             cbyte2 = zfirst[1] & 0xff;
  1708.           else
  1709.             cbyte2 = zsecond[0] & 0xff;
  1710.           cshort = (zfirst[0] & 0x7f) + (cbyte2 << 7);
  1711.           cmove = 2;
  1712.         }
  1713.  
  1714.           DEBUG_MESSAGE1 (DEBUG_PROTO,
  1715.                   "fgprocess_data: Packet short by %d",
  1716.                   cshort);
  1717.  
  1718.           /* Adjust the start of the buffer for the bytes used
  1719.          by the count.  */
  1720.           if (cfirst > cmove)
  1721.         {
  1722.           zfirst += cmove;
  1723.           cfirst -= cmove;
  1724.         }
  1725.           else
  1726.         {
  1727.           zfirst = zsecond + (cmove - cfirst);
  1728.           cfirst = csecond - (cmove - cfirst);
  1729.           csecond = 0;
  1730.         }
  1731.  
  1732.           /* Adjust the length of the buffer for the bytes we are
  1733.          not supposed to consider.  */
  1734.           cshort -= cmove;
  1735.           if (csecond >= cshort)
  1736.         csecond -= cshort;
  1737.           else
  1738.         {
  1739.           cfirst -= cshort - csecond;
  1740.           csecond = 0;
  1741.         }
  1742.  
  1743. #if DEBUG > 0
  1744.           /* This should not happen, but just in case.  */
  1745.           if (cfirst < 0)
  1746.         cfirst = 0;
  1747. #endif
  1748.         }
  1749.  
  1750.       if (! fgot_data (qdaemon, zfirst, (size_t) cfirst,
  1751.                zsecond, (size_t) csecond,
  1752.                -1, -1, (long) -1,
  1753.                INEXTSEQ (iGremote_ack) == iGsendseq,
  1754.                pfexit))
  1755.         return FALSE;
  1756.  
  1757.       /* If fgot_data told us that we were finished, get out.  */
  1758.       if (*pfexit)
  1759.         return TRUE;
  1760.  
  1761.       /* If we've been asked to return control packets, get out
  1762.          now.  */
  1763.       if (freturncontrol)
  1764.         {
  1765.           *pfexit = TRUE;
  1766.           return TRUE;
  1767.         }
  1768.  
  1769.       continue;
  1770.     }
  1771.  
  1772.       /* Handle control messages here. */
  1773. #if DEBUG > 1
  1774.       if (FDEBUGGING (DEBUG_PROTO)
  1775.       || (FDEBUGGING (DEBUG_ABNORMAL)
  1776.           && CONTROL_XXX (ab[IFRAME_CONTROL]) != RR))
  1777.     ulog (LOG_DEBUG, "fgprocess_data: Got control %s %d",
  1778.           azGcontrol[CONTROL_XXX (ab[IFRAME_CONTROL])],
  1779.           CONTROL_YYY (ab[IFRAME_CONTROL]));
  1780. #endif
  1781.  
  1782.       switch (CONTROL_XXX (ab[IFRAME_CONTROL]))
  1783.     {
  1784.     case CLOSE:
  1785.       /* The other side has closed the connection.  */
  1786.       if (fLog_sighup)
  1787.         {
  1788.           ulog (LOG_ERROR, "Received unexpected CLOSE packet");
  1789.           (void) fgsend_control (qdaemon, CLOSE, 0);
  1790.         }
  1791.       return FALSE;
  1792.     case RR:
  1793.       /* Acknowledge receipt of a packet.  This was already handled
  1794.          above, unless we are treating it as RJ.  */
  1795.       if (! fduprr)
  1796.         break;
  1797.       /* Fall through.  */
  1798.     case RJ:
  1799.       /* The other side dropped a packet.  Begin retransmission with
  1800.          the packet following the one acknowledged.  We don't
  1801.          retransmit the packets immediately, but instead wait
  1802.          for the first one to be acked.  This prevents us from
  1803.          sending an entire window several times if we get several
  1804.          RJ packets.  */
  1805.       iGremote_ack = CONTROL_YYY (ab[IFRAME_CONTROL]);
  1806.       iGretransmit_seq = INEXTSEQ (iGremote_ack);
  1807.       if (iGretransmit_seq == iGsendseq)
  1808.         iGretransmit_seq = -1;
  1809.       else
  1810.         {
  1811.           char *zpack;
  1812.  
  1813.           DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1814.                   "fgprocess_data: Remote reject: next %d resending %d",
  1815.                   iGsendseq, iGretransmit_seq);
  1816.  
  1817.           ++cGresent_packets;
  1818.           if (fduprr)
  1819.         ++cGremote_duprrs;
  1820.           else
  1821.         ++cGremote_rejects;
  1822.           ++cGerror_level;
  1823.           if (! fgcheck_errors (qdaemon))
  1824.         return FALSE;
  1825.           zpack = zgadjust_ack (iGretransmit_seq);
  1826.           if (! fsend_data (qdaemon->qconn, zpack,
  1827.                 CFRAMELEN + CPACKLEN (zpack),
  1828.                 TRUE))
  1829.         return FALSE;
  1830.         }
  1831.       break;
  1832.     case SRJ:
  1833.       /* Selectively reject a particular packet.  This is not used
  1834.          by UUCP, but it's easy to support.  */
  1835.       DEBUG_MESSAGE1 (DEBUG_PROTO | DEBUG_ABNORMAL,
  1836.               "fgprocess_data: Selective reject of %d",
  1837.               CONTROL_YYY (ab[IFRAME_CONTROL]));
  1838.       {
  1839.         char *zpack;
  1840.  
  1841.         ++cGresent_packets;
  1842.         ++cGremote_rejects;
  1843.         ++cGerror_level;
  1844.         zpack = zgadjust_ack (CONTROL_YYY (ab[IFRAME_CONTROL]));
  1845.         if (! fsend_data (qdaemon->qconn, zpack,
  1846.                   CFRAMELEN + CPACKLEN (zpack),
  1847.                   TRUE))
  1848.           return FALSE;
  1849.       }
  1850.       break;
  1851.     case INITC:
  1852.     case INITB:
  1853.     case INITA:
  1854.       /* Ignore attempts to reinitialize.  */
  1855.       break;
  1856.     }
  1857.  
  1858.       /* If we've been asked to return control packets, get out.  */
  1859.       if (freturncontrol)
  1860.     {
  1861.       *pfexit = TRUE;
  1862.       return TRUE;
  1863.     }
  1864.  
  1865.       /* Loop around to look for the next packet, if any.  */
  1866.     }
  1867.  
  1868.   /* There is no data left in the receive buffer.  */
  1869.   if (pcneed != NULL)
  1870.     *pcneed = CFRAMELEN;
  1871.   return TRUE;
  1872. }
  1873.  
  1874. /* Compute the 'g' protocol checksum.  This is unfortunately rather
  1875.    awkward.  This is the most time consuming code in the entire
  1876.    program.  It's also not a great checksum, since it can be fooled
  1877.    by some single bit errors.  */
  1878.  
  1879. /* Sorry about this knavery, but it speeds up the VAX code
  1880.    significantly.  It would be better to rewrite the whole routine in
  1881.    assembler.  */
  1882. #ifdef __GNUC__
  1883. #ifdef __vax__
  1884. #define VAX_ASM 1
  1885. #endif
  1886. #endif
  1887.  
  1888. #if VAX_ASM
  1889. #define ROTATE(i) \
  1890.   asm ("cvtwl %1,%0\n\trotl $1,%0,%0" : "=g" (i) : "g" (i))
  1891. #else
  1892. #define ROTATE(i) i += i + ((i & 0x8000) >> 15)
  1893. #endif
  1894.  
  1895. #define ITERATION \
  1896.       /* Rotate ichk1 left.  */ \
  1897.       ROTATE (ichk1); \
  1898.  \
  1899.       /* The guts of the checksum.  */ \
  1900.       b = BUCHAR (*z++); \
  1901.       if (b != 0) \
  1902.     { \
  1903.       ichk1 &= 0xffff; \
  1904.       ichk1 += b; \
  1905.       ichk2 += ichk1 ^ c; \
  1906.       if ((ichk1 >> 16) != 0) \
  1907.         ichk1 ^= ichk2; \
  1908.     } \
  1909.       else \
  1910.     { \
  1911.       ichk2 += ichk1 ^ c; \
  1912.       ichk1 ^= ichk2; \
  1913.     } \
  1914.  \
  1915.       --c
  1916.  
  1917. static int
  1918. igchecksum (z, c)
  1919.      register const char *z;
  1920.      register size_t c;
  1921. {
  1922.   register unsigned long ichk1, ichk2;
  1923.  
  1924.   ichk1 = 0xffff;
  1925.   ichk2 = 0;
  1926.  
  1927.   do
  1928.     {
  1929.       register unsigned int b;
  1930.  
  1931.       ITERATION;
  1932.       ITERATION;
  1933.       ITERATION;
  1934.       ITERATION;
  1935.     }
  1936.   while (c > 0);
  1937.  
  1938.   return ichk1 & 0xffff;
  1939. }
  1940.  
  1941. /* We use a separate function compute the checksum if the block is
  1942.    split around the end of the receive buffer since it occurs much
  1943.    less frequently and the checksum is already high up in the
  1944.    profiles.  These functions are almost identical, and this one
  1945.    actually only has a few more instructions in the inner loop.  */
  1946.  
  1947. static int
  1948. igchecksum2 (zfirst, cfirst, zsecond, csecond)
  1949.      const char *zfirst;
  1950.      size_t cfirst;
  1951.      const char *zsecond;
  1952.      size_t csecond;
  1953. {
  1954.   register unsigned long ichk1, ichk2;
  1955.   register const char *z;
  1956.   register size_t c;
  1957.  
  1958.   z = zfirst;
  1959.   c = cfirst + csecond;
  1960.  
  1961.   ichk1 = 0xffff;
  1962.   ichk2 = 0;
  1963.  
  1964.   do
  1965.     {
  1966.       register unsigned int b;
  1967.  
  1968.       ITERATION;
  1969.  
  1970.       /* If the first buffer has been finished, switch to the second.  */
  1971.       --cfirst;
  1972.       if (cfirst == 0)
  1973.     z = zsecond;
  1974.     }
  1975.   while (c > 0);
  1976.  
  1977.   return ichk1 & 0xffff;
  1978. }
  1979.